var fc5_entry = {
    /**
     * Save translation entry
     * @param {Object} data - Translation data to save
     */
    saveTranslate: function (data) {
        fc5_utils.showLoading();
        
        // 创建一个新对象来合并数据
        var requestData = {
            action: 'entry_save_entry'
        };
        for (var key in data) {
            if (data.hasOwnProperty(key)) {
                requestData[key] = data[key];
            }
        }

        // 添加 token 和 site_id 参数，从 sessionStorage 获取
        var token = sessionStorage.getItem('fc5_token');
        var siteId = sessionStorage.getItem('fc5_site_id');
        if (token) {
            requestData.token = token;
        }
        if (siteId) {
            requestData.site_id = siteId;
        }

        fc5_utils.post(
            falcon5_ajax_config.ajax_url,
            requestData,
            function (response) {
                fc5_utils.hideLoading();
                
                // 恢复保存按钮状态
                var saveBtn = document.getElementById('save');
                if (saveBtn) {
                    saveBtn.disabled = false;
                    saveBtn.textContent = saveBtn.dataset.originalText || 'Save';
                    saveBtn.classList.remove('loading');
                }

                if (response.code === 1) {
                    var id = data.original_id;
                    var translated = data.translated;
                    
                    // Update all matching fc5 elements
                    var fc5Elements = document.querySelectorAll('fc5[id="' + id + '"]');
                    for (var i = 0; i < fc5Elements.length; i++) {
                        var fc5 = fc5Elements[i];
                        fc5.setAttribute('translated', translated);
                        fc5.innerHTML = translated;
                        
                        // Remove edit icon if exists
                        var editSpan = fc5.querySelector('fc5-span');
                        if (editSpan) {
                            editSpan.parentNode.removeChild(editSpan);
                        }
                    }
                    
                    if (response.msg) {
                        fc5_utils.showTip(response.msg);
                    } else {
                        fc5_utils.showTip('Translation saved successfully');
                    }
                } else {
                    console.error('Failed to save translation:', response.msg);
                    fc5_utils.showTip(response.msg || 'Failed to save translation');
                }

                var closeBtn = document.querySelector('.close-reveal-modal');
                if (closeBtn) {
                    closeBtn.click();
                }
            },
            function (error) {
                fc5_utils.hideLoading();
                
                // 恢复保存按钮状态
                var saveBtn = document.getElementById('save');
                if (saveBtn) {
                    saveBtn.disabled = false;
                    saveBtn.textContent = saveBtn.dataset.originalText || 'Save';
                    saveBtn.classList.remove('loading');
                }
                
                console.error('Request failed:', error);
                
                // 检查是否为401或403状态码，如果是则跳转到登录页面
                if (error && error.message && (error.message.includes('Status: 401') || error.message.includes('Status: 403'))) {
                    window.location.href = falcon5_ajax_config.fc5_login_url;
                    return;
                }
                
                fc5_utils.showTip(typeof error === 'string' ? error : 'Failed to save translation');
            }
        );
    }
};

var fc5_edit = {
    /**
     * Initialize the application
     */
    init: function () {
        // 使用事件委托处理所有 fc5 相关的事件
        var self = this;
        document.addEventListener('mouseover', function(e) {
            self.handleMouseOver(e);
        });
        document.addEventListener('mouseout', function(e) {
            self.handleMouseOut(e);
        });
        document.addEventListener('click', function(e) {
            self.handleClick(e);
        });

        // 初始化时移除所有可能存在的编辑图标
        this.clearAllEditIcons();
    },

    /**
     * 处理鼠标悬停事件
     * @param {MouseEvent} e - 鼠标事件对象
     */
    handleMouseOver: function(e) {
        var fc5Element = this.findClosestFc5(e.target);
        if (!fc5Element || fc5Element.querySelector('fc5-span')) {
            return;
        }

        // 清除其他元素的编辑图标
        this.clearAllEditIcons();

        // 获取原始文本
        var text = fc5Element.textContent.trim();
        
        // 创建编辑图标元素
        var editSpan = document.createElement('fc5-span');
        editSpan.innerHTML = 
            '<div class="fc5-editor-action-hover-container">' +
                '<fc5-edit title="Translate" class="fc5-icon fc5-edit-translation" style="display: inline-block;"></fc5-edit>' +
            '</div>';

        // 插入编辑图标
        fc5Element.insertBefore(editSpan, fc5Element.firstChild);
    },

    /**
     * 处理鼠标离开事件
     * @param {MouseEvent} e - 鼠标事件对象
     */
    handleMouseOut: function(e) {
        var fc5Element = this.findClosestFc5(e.target);
        var relatedTarget = e.relatedTarget;
        
        // 检查鼠标是否真的离开了 fc5 元素
        if (fc5Element && !this.contains(fc5Element, relatedTarget)) {
            this.clearEditIcon(fc5Element);
        }
    },

    /**
     * 处理点击事件
     * @param {MouseEvent} e - 鼠标事件对象
     */
    handleClick: function(e) {
        // 处理编辑按钮点击
        if (this.matches(e.target, 'fc5-edit')) {
            e.preventDefault();
            e.stopPropagation(); // 阻止事件冒泡
            var fc5Parent = this.findClosestFc5(e.target);
            if (fc5Parent) {
                this.showEditModal(fc5Parent);
            }
        }
    },

    /**
     * 显示编辑模态框
     * @param {HTMLElement} fc5Element - fc5 元素
     */
    showEditModal: function(fc5Element) {
        var id = fc5Element.getAttribute('id') || '';
        var original = fc5Element.getAttribute('original') || '';
        var translated = fc5Element.getAttribute('translated') || '';
        var original_lang = fc5Element.getAttribute('original_lang') || '';
        var translated_lang = fc5Element.getAttribute('translated_lang') || '';

        // 创建模态框 HTML
        var html = 
            '<div id="myModal" class="reveal-modal">' +
                '<div style="margin: 5px;display: block;">' +
                    '<input type="hidden" id="fc5-edit-id" name="id" value="' + this.escapeHtml(id) + '">' +
                    '<input type="hidden" id="fc5-edit-original-lang" name="original_lang" value="' + this.escapeHtml(original_lang) + '">' +
                    '<input type="hidden" id="fc5-edit-translated-lang" name="translated_lang" value="' + this.escapeHtml(translated_lang) + '">' +
                    '<div class="fc5-editor-input">' +
                        '<div>original:</div>' +
                        '<input type="text" id="fc5-edit-original" name="original" value="' + this.escapeHtml(original) + '" disabled>' +
                    '</div>' +
                    '<div class="fc5-editor-input">' +
                        '<div>translated:</div>' +
                        '<input type="text" id="fc5-edit-translated" name="translated" value="' + this.escapeHtml(translated) + '">' +
                    '</div>' +
                    '<div class="fc5-editor-button-container">' +
                        '<button id="save" class="fc5-save-btn" data-loading-text="Saving...">Save</button>' +
                    '</div>' +
                '</div>' +
                '<a class="close-reveal-modal">×</a>' +
            '</div>';

        // 移除已存在的模态框
        var oldModal = document.querySelector('.reveal-modal');
        if (oldModal) {
            oldModal.parentNode.removeChild(oldModal);
        }
        
        // 添加新的模态框
        var tempDiv = document.createElement('div');
        tempDiv.innerHTML = html;
        document.body.appendChild(tempDiv.firstChild);
        
        var modal = document.getElementById('myModal');
        var saveBtn = document.getElementById('save');

        // 添加按钮点击事件处理
        saveBtn.addEventListener('click', function(e) {
            e.preventDefault();
            if (this.disabled) return;
            
            // 禁用按钮并显示加载状态
            this.disabled = true;
            var originalText = this.textContent;
            this.textContent = this.getAttribute('data-loading-text');
            this.classList.add('loading');
            
            // 调用保存处理
            fc5_edit.handleSave();
            
            // 保存按钮引用和原始文本，以便后续恢复
            this.dataset.originalText = originalText;
        });

        try {
            if (window.Reveal) {
                new Reveal(modal, {
                    animation: 'fadeAndPop',
                    animationSpeed: 300,
                    closeOnBackgroundClick: true
                });
            } else {
                modal.style.cssText = 'display: block; visibility: visible; top: 100px; opacity: 1;';
            }
        } catch (error) {
            console.error('Reveal error:', error);
            modal.style.cssText = 'display: block; visibility: visible; top: 100px; opacity: 1;';
        }
    },

    /**
     * 处理保存操作
     */
    handleSave: function() {
        var data = {
            'original_id': document.getElementById('fc5-edit-id').value,
            'original': document.getElementById('fc5-edit-original').value,
            'translated': document.getElementById('fc5-edit-translated').value,
            'original_lang': document.getElementById('fc5-edit-original-lang').value,
            'translated_lang': document.getElementById('fc5-edit-translated-lang').value,
            'uri_path': fc5_utils.get_uri_path()
        };
        fc5_entry.saveTranslate(data);
    },

    /**
     * 清除指定 fc5 元素的编辑图标
     * @param {HTMLElement} fc5Element - fc5 元素
     */
    clearEditIcon: function(fc5Element) {
        var editSpan = fc5Element.querySelector('fc5-span');
        if (editSpan) {
            editSpan.parentNode.removeChild(editSpan);
        }
    },

    /**
     * 清除所有 fc5 元素的编辑图标
     */
    clearAllEditIcons: function() {
        var spans = document.querySelectorAll('fc5 fc5-span');
        for (var i = 0; i < spans.length; i++) {
            var span = spans[i];
            span.parentNode.removeChild(span);
        }
    },

    /**
     * 查找最近的 fc5 元素
     * @param {HTMLElement} element - 起始元素
     * @returns {HTMLElement|null} - 找到的 fc5 元素或 null
     */
    findClosestFc5: function(element) {
        while (element && element.nodeName.toLowerCase() !== 'fc5') {
            element = element.parentNode;
        }
        return element;
    },

    /**
     * 检查元素是否包含另一个元素
     * @param {HTMLElement} parent - 父元素
     * @param {HTMLElement} child - 子元素
     * @returns {boolean} - 是否包含
     */
    contains: function(parent, child) {
        if (!parent || !child) {
            return false;
        }
        return parent.contains ? parent.contains(child) : !!(parent.compareDocumentPosition(child) & 16);
    },

    /**
     * 检查元素是否匹配选择器
     * @param {HTMLElement} element - 要检查的元素
     * @param {string} selector - CSS选择器
     * @returns {boolean} - 是否匹配
     */
    matches: function(element, selector) {
        if (!element) return false;
        var matchesFunc = element.matches || 
                         element.webkitMatchesSelector || 
                         element.mozMatchesSelector || 
                         element.msMatchesSelector;
        return matchesFunc ? matchesFunc.call(element, selector) : false;
    },

    /**
     * 转义 HTML 特殊字符
     * @param {string} unsafe - 不安全的字符串
     * @returns {string} - 安全的字符串
     */
    escapeHtml: function(unsafe) {
        if (typeof unsafe !== 'string') return '';
        return unsafe
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }
};


var fc5_url = {
    getParameterByName: function (name, url) {
        if (!url) url = window.location.href;
        name = name.replace(/[\[\]]/g, "\\$&");
        var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
            results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, " "));
    },

    addQueryParam: function (url, key, value) {
        var a = document.createElement('a');
        a.href = url;
        var params = new URLSearchParams(a.search);
        if (!params.has(key)) {
            params.set(key, value);
            a.search = params.toString();
        }
        return a.href;
    },

    /**
     * 添加常用参数到URL
     * @param {string} url - 原始URL
     * @returns {string} - 添加了常用参数的URL
     */
    addCommonParams: function(url) {
        var result = url;
        
        // 添加language_edit参数
        result = this.addQueryParam(result, 'language_edit', '1');
        
        // 从sessionStorage获取并添加token和site_id
        var token = sessionStorage.getItem('fc5_token');
        var siteId = sessionStorage.getItem('fc5_site_id');
        
        if (token) {
            result = this.addQueryParam(result, 'token', token);
        }
        if (siteId) {
            result = this.addQueryParam(result, 'site_id', siteId);
        }
        
        return result;
    },

    /**
     * 从 URL 中删除指定参数
     * @param {string} url - URL字符串
     * @param {Array} paramsToRemove - 要删除的参数数组
     * @returns {string} - 处理后的URL
     */
    removeParams: function(url, paramsToRemove) {
        var urlParts = url.split('?');
        if (urlParts.length < 2) return url;

        var baseUrl = urlParts[0];
        var query = urlParts[1];
        var params = query.split('&');
        var newParams = [];

        for (var i = 0; i < params.length; i++) {
            var param = params[i].split('=')[0];
            var shouldKeep = true;
            for (var j = 0; j < paramsToRemove.length; j++) {
                if (param === paramsToRemove[j]) {
                    shouldKeep = false;
                    break;
                }
            }
            if (shouldKeep && params[i]) {
                newParams.push(params[i]);
            }
        }

        return baseUrl + (newParams.length ? '?' + newParams.join('&') : '');
    },

    /**
     * 保存 token 和 site_id 参数到 sessionStorage
     */
    saveAuthParams: function() {
        var url = window.location.href;
        
        // 获取 token 和 site_id 参数
        var token = this.getParameterByName('token', url);
        var siteId = this.getParameterByName('site_id', url);
        
        // 如果参数存在，则保存到 sessionStorage
        var paramsChanged = false;
        if (token) {
            sessionStorage.setItem('fc5_token', token);
            paramsChanged = true;
        }
        if (siteId) {
            sessionStorage.setItem('fc5_site_id', siteId);
            paramsChanged = true;
        }

        // 如果有参数被保存，则从 URL 中删除这些参数
        // if (paramsChanged) {
        //     var newUrl = this.removeParams(window.location.href, ['token', 'site_id']);
        //     // 使用 history.replaceState 更新 URL，不会导致页面刷新
        //     if (window.history && window.history.replaceState) {
        //         window.history.replaceState({}, '', newUrl);
        //     }
        // }
    },

    init: function () {
        // 初始化时保存 token 和 site_id 参数
        this.saveAuthParams();
        if (fc5_url.getParameterByName('language_edit')) {
            document.body.addEventListener("click", function(event) {
                var target = event.target || event.srcElement;
                
                // 如果点击的是编辑按钮或其容器，直接返回
                if (target.matches('fc5-edit') || 
                    target.matches('fc5-span') || 
                    target.matches('.fc5-editor-action-hover-container')) {
                    return;
                }
                
                // 处理其他链接点击
                while (target && target.tagName !== "A") {
                    target = target.parentNode;
                }
                if (target && target.tagName === "A" && target.href) {
                    var newUrl = fc5_url.addCommonParams(target.href);
                    event.preventDefault();
                    window.location.href = newUrl;
                }
            });
        }
    }

}

// 初始化应用
document.addEventListener('DOMContentLoaded', function() {
    fc5_edit.init();
    fc5_url.init();

});